package com.syh.jn.scm.infrastructure.repository.impl.operation.system;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.core.expction.DataModelException;
import com.syh.jn.scm.domain.operation.entity.system.Dict;
import com.syh.jn.scm.domain.operation.repository.system.DictRepository;
import com.syh.jn.scm.dto.operation.system.dict.DictVo;
import com.syh.jn.scm.infrastructure.repository.model.base.DictModel;
import com.syh.jn.scm.infrastructure.repository.model.base.DictTypeModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

/**
 * Date:2018/7/13
 * Author:Clown
 * Desc;
 */
@Repository
public class DictRepositoryImpl extends AbstractAggregateRepository<Dict,DictModel,Long> implements DictRepository {

  @Override
  public Long add(Dict dict){
    ExtAssert.notNull(dict,"对象不存在");

    //判断分类是否存在
    if(dict.getCategoryId()!=null){
      DictTypeModel father = this.hibernateTemplate.get(DictTypeModel.class,dict.getCategoryId());
      if (father == null) {
        throw new DataModelException("父级分类不存在");
      }
    }

    DictModel dictModel = new DictModel();
    ExtBeanUtils.copyProperties(dict,dictModel);
    dict.setId((Long) this.hibernateTemplate.save(dictModel));
    return dict.getId();
  }

  @Override
  public void update(Dict dict){
    ExtAssert.notNull(dict,"对象不存在");

    //判断分类是否存在
    if(dict.getCategoryId()!=null){
      DictTypeModel father = this.hibernateTemplate.get(DictTypeModel.class,dict.getCategoryId());
      if (father == null) {
        throw new DataModelException("父级分类不存在");
      }
    }

    DictModel dictModel = this.hibernateTemplate.get(DictModel.class,dict.getId());
    ExtBeanUtils.copyProperties(dict,dictModel);
    this.hibernateTemplate.update(dictModel);
  }

  @Override
  protected SQL getViewSql() {
    return new SQL() {{
      SELECT(
              SQLAliasGenerateUtil.aliasGenerate(DictModel.class, "dict", null)
      );
      FROM("T_BASE_DICT dict");
    }};
  }

  @Override
  protected Class getViewObject() {
    return DictVo.class;
  }

  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    Map<String, String> params = new HashMap<>();
    params.put("id", "dict.ID");
    params.put("name", "dict.NAME");
    params.put("status", "dict.STATUS");
    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return params.get(propertyName);
    });
    return parse;
  }
}
